package pl.edu.pb.wi.pwnography.session;

import java.util.LinkedList;
import java.util.List;
import java.util.logging.Logger;

import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.stereotype.Component;

import pl.edu.pb.wi.pwnography.model.ParsedData;

/*
 * Bez proxyMode nie pójdzie, ponieważ controllery to singletony, więc aby można
 * było coś w nie wstrzyknąć musiałyby być w zakresie request. Drugim
 * rozwiązaniem jest właśnie to co jest tu niżej. Rozwiązanie korzysta z CGLIB.
 */
@Component
@Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS)
public class FileList {
    private static final Logger log = Logger
	    .getLogger(FileList.class.getName());
    private List<ParsedData> fileList;
    private int activeFileId;

    public FileList() {
	fileList = new LinkedList<ParsedData>();
	activeFileId = -1;
    }

    public List<ParsedData> getFileList() {
	return fileList;
    }

    public int getActiveFileId() {
	return activeFileId;
    }

    public Integer getCurrentRevision() {
	return (getActiveFile() == null) ? null : getActiveFile()
		.getCurrentRevision();
    }

    public void setActiveFileId(int id) {
	log.info(String.format("Changing active file: [old] %d -> %d [new].",
		activeFileId, id));

	if (id < fileList.size() && id >= 0)
	    activeFileId = id;
    }

    public ParsedData getActiveFile() {
	return getParsedData(getActiveFileId());
    }

    public void addFile(ParsedData file) {
	log.info("New file is going to be added to file list.");

	fileList.add(file);
	setActiveFileId(fileList.size() - 1);
    }

    public ParsedData getParsedData(int index) {
	return (index < fileList.size() && index >= 0) ? fileList.get(index)
		: null;
    }

    public ParsedData remove(int index) {
	log.info(String.format(
		"File %d is going to be removed from file list.", index));

	if (index < fileList.size() && index >= 0) {
	    ParsedData pd = fileList.remove(index);

	    if (fileList.size() == 0) {
		activeFileId = -1;
	    } else {
		activeFileId = fileList.size() - 1;
	    }

	    return pd;
	} else {
	    return null;
	}
    }

}
